// pages/order/index.js
const app = getApp();
const fetchSev = require("../../utils/util.js").fetchSev;
const addCartUrl = require("../../config.js").addCartUrl;
const getSkuDetail = require("../../config.js").getSkuDetail;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 500,

    
    maxWeight: '',
    minWeight: '',
    num: 1,
    remark: '',

    currentSku: {},  // 从上级页面传递过来的sku
    skuDetail: {},   // 通过getInfo接口获取到的sku

    startTime: 0,   // 禁止连续点击“加入购物车”
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('页面刷新');
    // 重置
    const currentSku = app.globalData.currentSku;
    console.log('来自父级页面的sku', currentSku);
    this.setData({ startTime: 0});

    // this.setData({ currentSku: currentSku });
    this.setData({ maxWeight: currentSku.max_weight || 0});
    this.setData({ minWeight: currentSku.min_weight || 0});
    this.setData({remark: ''});
    this.setData({num: 1});

    // 获取小码详情
    // id =&department=&metal_id=&max_weight=&min_weight
    let data = {
      id: currentSku.sku_id || currentSku.id,
      department: currentSku.department,
      metal_id: currentSku.metal_id,
      max_weight: currentSku.max_weight,
      min_weight: currentSku.min_weight
    }
    console.log('获取小码详情的5个条件', data);
    fetchSev(getSkuDetail, "GET", data, res=>{
      console.log('小码详情', res);
      this.setData({skuDetail: res});
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  // 1-输入克重范围
  _minWeightChange: function(e) {
    this.setData({minWeight: e.detail.value});
    console.log('minWeight', this.data.minWeight);
  },
  _maxWeightChange: function(e) {
    this.setData({ maxWeight: e.detail.value });
    console.log('maxWeight', this.data.maxWeight);
  },
  _minWeightClear: function(e) {
    this.setData({ minWeight: e.detail.value });
  },
  _maxWeightClear: function (e) {
    this.setData({ maxWeight: e.detail.value });
  },

  // 2-数量
  _numChange: function(e) {
    let val = e.detail.value;
    // 数量不能有小数点
    val = val.split('.')[0];
    this.setData({ num: val });
  },
  // 减1
  _numSubClick: function() {
    let num = this.data.num;
    num === '' ? num = 0 : num = parseInt(num);
    if (num == 0) return false;
    num = num - 1;
    this.setData({ num: num});
    console.log(this.data.num);
  },
  // 加1
  _numAddClick: function() {
    let num = this.data.num;
    num === '' ? num = 0 : num = parseInt(num);
    num = num + 1;
    this.setData({ num: num });
    console.log(this.data.num);
  },

  // 3-备注
  _remarkChange: function(e) {
    this.setData({ remark: e.detail.value });
  },
  _remarkFocus: function(e) {
    console.log(e);
    this.setData({ remark: ''});
  },


  // 4-加入购物车   {"sku_id":26448,"max_weight":5,"min_weight":4,"num":2,"department": "80","metal_id": "1000002"}
  submit: function() {
    // 禁止用户连续点击 
    let now = Date.now();
    if (now - this.data.startTime < 5000) {
      // 5秒内不能重复点击
      return false;
    }
    this.setData({startTime: now});

    const curSku = this.data.skuDetail;

    const data = {
      sku_id: this.data.skuDetail.id,
      department: this.data.skuDetail.department ,
      metal_id: this.data.skuDetail.metal_id || '',
      spu_id: this.data.skuDetail.spu_id,

      max_weight: this.data.maxWeight,
      min_weight: this.data.minWeight,
      num: this.data.num,
      remark: this.data.remark,

      type: '1', // 变化的字段
      customer_id: '',
      weight: (parseFloat(this.data.maxWeight) + parseFloat(this.data.minWeight)) * parseInt(this.data.num) / 2,
      wechat_id: ''
    }
    
    // 表单验证
    if (data.max_weight == '' || data.min_weight == '') {
      wx.showToast({
        title: '克重范围不能为空',
        icon: 'none'
      });
      return;
    }
    if (data.num == '') {
      wx.showToast({
        title: '数量不能为空或零',
        icon: 'none'
      });
      return;
    }
    if (parseFloat(data.min_weight) > parseFloat(data.max_weight)) {
      wx.showToast({
        title: '克重范围有误',
        icon: 'none'
      });
      return;
    }
    // 购买数量不能小于1
    if (parseInt(data.num) < 1) {
      wx.showToast({
        title: '数量不能小于1',
        icon: 'none'
      });
      return;
    }
    // 克重不能超出范围
    if (parseFloat(data.min_weight) < parseFloat(curSku.min_weight || 0)) {
      wx.showToast({
        title: '最小克重不能超出默认克重范围',
        icon: 'none'
      });
      return;
    }
    if (parseFloat(data.max_weight) > parseFloat(curSku.max_weight || 0)) {
      wx.showToast({
        title: '最大克重不能超出默认克重范围',
        icon: 'none'
      });
      return;
    }

    console.log('加入购物车', data);
    // 提交数据
    fetchSev(addCartUrl, "POST", data, function(res) {
      console.log('加入购物车', res);
      if(res) {
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 2000,
          complete: function () {
            setTimeout(()=>{
              wx.navigateBack({
                delta: 1
              });
            }, 2000)            
          }
        });
      }      
    })
  }
})